package cn.itcast.bos.service.base.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {

	@Autowired
	private CourierRepository courierRepository;

	@RequiresPermissions("courier:add")
	@Override
	public void add(Courier courier) {
		courierRepository.save(courier);
	}

	@Override
	public Page<Courier> findPageData(Specification<Courier> specification, Pageable pageable) {
		return courierRepository.findAll(specification, pageable);
	}

	@Override
	public void del(String[] idsArr) {
		for (String id : idsArr) {
			courierRepository.del(Integer.parseInt(id));
		}
	}

	@Override
	public void recover(String[] idsArr) {
		for (String id : idsArr) {
			courierRepository.recover(Integer.parseInt(id));
		}
	}

	@Override
	public List<Courier> findNoAssociation() {
		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return predicate;
			}
		};
		return courierRepository.findAll(specification);
	}

	@Override
	public List<Courier> findCourierByFixedAreaId(String fixedAreaId) {
		List<Courier> list = new ArrayList<Courier>();
		List<Courier> Couriers = courierRepository.findAll();
		for (Courier courier : Couriers) {
			Set<FixedArea> fixedAreas = courier.getFixedAreas();
			for (FixedArea fixedArea : fixedAreas) {
				if(fixedAreaId.equals(fixedArea.getId())){
					list.add(courier);
				}
			}
		}
		return list;
	}

	@Override
	public List<Courier> findAll() {
		
		return courierRepository.findAll();
	}

}
